//
//  discoverAddController.m
//  Focus
//
//  Created by xwc on 14-10-28.
//  Copyright (c) 2014年 lanou3g.com 蓝鸥科技. All rights reserved.
//

#import "SectionViewController.h"
#import "discoverAddCell.h"
#import "discoverTitleController.h"
#import "SearchBarBlockVC.h"
#import "recommendController.h"
#import "WebImageViewController.h"
#import "ImageViewController.h"
#import "discoverAddController.h"
@interface SectionViewController ()<UITableViewDataSource,UITableViewDelegate,UISearchBarDelegate>

@property (nonatomic, retain)UITableView *tableView;
@property (nonatomic, retain)UISearchBar *searchBar;
@property (nonatomic, retain)NSMutableArray *array;
@property (nonatomic, retain)NSMutableArray *searchArray;
@property (nonatomic, retain)NSDictionary *blockDic;
@property (nonatomic, retain)NSMutableArray *blockArray;
@end

@implementation SectionViewController

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
        
        self.searchArray = [NSMutableArray array];
        self.blockDic = [NSDictionary dictionary];
        self.blockArray = [NSMutableArray array];
        
    }
    return self;
}

- (void)viewDidLoad
{
    [super viewDidLoad];
    // Do any additional setup after loading the view.
#pragma mark -
#pragma mark - 导航栏右边自定义button
    UIButton *left = [UIButton buttonWithType:UIButtonTypeCustom];
    left.frame = CGRectMake(0, 0, 40, 40);
    [left setImage:[UIImage imageNamed:@"back.png"] forState:UIControlStateNormal];
    [left addTarget:self action:@selector(leftButtonAction:) forControlEvents:UIControlEventTouchUpInside];
    self.navigationItem.leftBarButtonItem = [[[UIBarButtonItem alloc]initWithCustomView:left]autorelease];
#pragma mark -
#pragma mark - 导航栏标题设置
    UILabel *title = [[UILabel alloc]initWithFrame:CGRectMake(0, 0, 70, 30)];
    
    title.textColor = [UIColor whiteColor];
    title.font = [UIFont systemFontOfSize:18];
    title.textAlignment =  NSTextAlignmentCenter;
    title.backgroundColor = [UIColor clearColor];
    self.navigationItem.titleView = title;
    [title release];
    
    
    //checkPlist
    [self checkPlist];
    
    //页面布局
    [self setupViews];
}
#pragma mark -
#pragma mark - 左边button点击事件
-(void)leftButtonAction:(UIButton *)sender{
    [self.navigationController popToRootViewControllerAnimated:YES];
}

- (void)setupViews
{
    self.tableView = [[UITableView alloc] initWithFrame:self.view.bounds style:UITableViewStylePlain];
    self.tableView.delegate = self;
    self.tableView.dataSource = self;
    [self.view addSubview:self.tableView];
    [_tableView release];
    
    self.navigationItem.rightBarButtonItem = [[[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemSearch target:self action:@selector(barButtonItemAction:)] autorelease];
    self.navigationItem.rightBarButtonItem.tintColor = [UIColor blackColor];
}

- (void)viewWillAppear:(BOOL)animated
{
    self.navigationController.navigationBarHidden = NO;
    self.tabBarController.tabBar.hidden = YES;
}

- (void)checkPlist
{
    NSString *documentPath_sort = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) lastObject];
    NSString *filePath_sort = [documentPath_sort stringByAppendingPathComponent:@"apiBlockSorts.plist"];
    NSMutableDictionary *readDic_sort = [NSMutableDictionary dictionaryWithContentsOfFile:filePath_sort];
    self.array = [[readDic_sort objectForKey:@"_root"][self.numberSons] objectForKey:@"sons"];
    
    for (NSDictionary *dic in self.array) {
        self.blockDic = dic;
        [self.blockArray addObject:self.blockDic];
    }
    
    NSString *documentPath = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) lastObject];
    NSString *filePath = [documentPath stringByAppendingPathComponent:@"rootBlocks.plist"];
    NSDictionary *readDic = [NSDictionary dictionaryWithContentsOfFile:filePath];
    
    if (readDic == nil) {
        NSString *str = [[NSBundle mainBundle] pathForResource:@"rootBlocks" ofType:@"plist"];
        NSDictionary *dic = [NSDictionary dictionaryWithContentsOfFile:str];
        
        BOOL result = [dic writeToFile:filePath atomically:YES];
        if (result) {
            NSLog(@"rootBlocks.plist归档成功");
        } else {
            NSLog(@"rootBlocks.plist归档失败");
        }
    }
}
#pragma mark 搜索栏
- (void)barButtonItemAction:(UIBarButtonItem *)barButton
{
    self.searchBar = [[UISearchBar alloc] initWithFrame: CGRectMake(0, 20, self.view.bounds.size.width, 40)];
    self.searchBar.placeholder = @"搜索你感兴趣的内容";
    [self.searchBar becomeFirstResponder];
    self.searchBar.delegate = self;
    self.searchBar.showsCancelButton = YES;
    [self.navigationController.view addSubview: self.searchBar];
    
    SearchBarBlockVC *searVC = [[SearchBarBlockVC alloc]init];
    
    for (NSDictionary *dic in self.array) {
        NSString *str = [dic objectForKey:@"block_title"];
        [self.searchArray addObject:str];
    }
    
    searVC.searchArray = self.searchArray;
    searVC.array = self.array;
    searVC.blockArray = self.blockArray;
    [self.navigationController pushViewController:searVC animated:YES];
    [self.tableView reloadData];
    [searVC release];
}

- (void)searchBarCancelButtonClicked:(UISearchBar *)searchBar
{
    [self.searchBar removeFromSuperview];
    
    [self.navigationController popToRootViewControllerAnimated:YES];
}

- (void)searchBar:(UISearchBar *)searchBar textDidChange:(NSString *)searchText
{
    NSLog(@"查询内容改变");
}

- (void)dealloc
{
    [_array release];
    [_searchBar release];
    [_tableView release];
    [super dealloc];
}

#pragma mark --- tableView协议方法

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return self.view.frame.size.height / 8;
}




- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    NSArray *array = [self.array[section] objectForKey:@"sons"];
    
    return [array count];
}

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return self.array.count;
}

- (NSString *)tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section
{
    NSString *str = [self.array[section] objectForKey:@"block_title"];
    return str;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    NSArray *array = [self.array[indexPath.section] objectForKey:@"sons"];
    
    discoverAddCell *cell = [tableView dequeueReusableCellWithIdentifier:@"nrkadd"];
    if (cell == nil) {
        cell = [[[discoverAddCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:@"nrkadd"]autorelease];;
    }
    
    cell.textLabel.text = [array[indexPath.row] objectForKey:@"block_title"];
    
#pragma mark 根据rootBlocks.plist来判断图片的mark情况
    UIImage *image_jiahao = [UIImage imageNamed:@"jiahao.png"];
    UIImage *image_duigou = [UIImage imageNamed:@"duigou.png"];
    
#pragma mark 根据apiBlockSorts.plist 里面的 need_userinfo 来判断是否mark
    if ([[array[indexPath.row] objectForKey:@"need_userinfo"] isEqualToString:@"YES"]) {
        [cell.markButton setImage:image_duigou forState:UIControlStateNormal];
    } else {
        [cell.markButton setImage:image_jiahao forState:UIControlStateNormal];
    }
    
    [cell.markButton addTarget:self action:@selector(markButtonClicked:) forControlEvents:UIControlEventTouchUpInside];
    cell.markButton.tag = indexPath.row;
    
    return cell;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    NSArray *array = [self.array[indexPath.section] objectForKey:@"sons"];
    
    discoverTitleController *discoverTitle = [[discoverTitleController alloc] init];
    discoverTitle.api_url = [array[indexPath.row] objectForKey:@"api_url"];
    discoverTitle.pk = [array[indexPath.row] objectForKey:@"pk"];
    
    discoverTitle.type = [array[indexPath.row] objectForKey:@"data_type"];
    if ([discoverTitle.pk isEqualToString:@"10516"] || [discoverTitle.pk isEqualToString:@"10721"] || [discoverTitle.pk isEqualToString:@"11365"] || [discoverTitle.pk isEqualToString:@"1"]) {
        WebImageViewController *webImageVC = [[WebImageViewController alloc]init];
        webImageVC.api_url = [array[indexPath.row] objectForKey:@"api_url"];
        [self presentViewController:webImageVC animated:YES completion:^{
        }];
        
    } else if ([discoverTitle.type isEqualToString:@"photo"]) {
        ImageViewController *imageVC = [[ImageViewController alloc] init];
        imageVC.api_url = [array[indexPath.row] objectForKey:@"api_url"];
        
        [self presentViewController:imageVC animated:YES completion:^{
            
        }];
    }
    else {
        
        [self presentViewController:discoverTitle animated:YES completion:^{
            
        }];
        
    }
    
    [discoverTitle release];
}

- (void)markButtonClicked:(UIButton *)button
{
    UIImage *image_jiahao = [UIImage imageNamed:@"jiahao.png"];
    UIImage *image_duigou = [UIImage imageNamed:@"duigou.png"];
    if (button.imageView.image == image_jiahao) {
        [button setImage:image_duigou forState:UIControlStateNormal];
        
#pragma mark 添加收藏
        
#pragma mark apiBlockSorts.plist 添加
        NSString *documentPath_sort = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) lastObject];
        NSString *filePath_sort = [documentPath_sort stringByAppendingPathComponent:@"apiBlockSorts.plist"];
        NSMutableDictionary *readDic_sort = [NSMutableDictionary dictionaryWithContentsOfFile:filePath_sort];
        
        [self.array[button.tag] setObject:@"YES" forKey:@"need_userinfo"];
        [[readDic_sort objectForKey:@"_root"][self.numberSons] setObject:self.array forKey:@"sons"];
        BOOL result_sort = [readDic_sort writeToFile:filePath_sort atomically:YES];
        if (result_sort) {
            NSLog(@"添加apiBlockSorts成功");
        } else {
            NSLog(@"添加apiBlockSorts失败");
        }
        
#pragma mark rootBlocks.plist 添加
        NSString *documentPath = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) lastObject];
        NSString *filePath = [documentPath stringByAppendingPathComponent:@"rootBlocks.plist"];
        NSMutableDictionary *readDic = [NSMutableDictionary dictionaryWithContentsOfFile:filePath];
        
        NSMutableArray *arr = [NSMutableArray arrayWithArray:[readDic objectForKey:@"blocksData"]];
        [arr addObject:self.array[button.tag]];
        [readDic setObject:arr forKey:@"blocksData"];
        BOOL result = [readDic writeToFile:filePath atomically:YES];
        
        if (result) {
            NSLog(@"添加rootBlocks成功");
        } else {
            NSLog(@"添加rootBlocks失败");
        }
        
    } else {
        [button setImage:image_jiahao forState:UIControlStateNormal];
        
        //取消收藏
        
        //apiBlockSorts.plist 删除
        NSString *documentPath_sort = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) lastObject];
        NSString *filePath_sort = [documentPath_sort stringByAppendingPathComponent:@"apiBlockSorts.plist"];
        NSMutableDictionary *readDic_sort = [NSMutableDictionary dictionaryWithContentsOfFile:filePath_sort];
        
        [self.array[button.tag] setObject:@"NO" forKey:@"need_userinfo"];
        [[readDic_sort objectForKey:@"_root"][self.numberSons] setObject:self.array forKey:@"sons"];
        BOOL result_sort = [readDic_sort writeToFile:filePath_sort atomically:YES];
        if (result_sort) {
            NSLog(@"删除apiBlockSorts成功");
        } else {
            NSLog(@"删除apiBlockSorts失败");
        }
        
        //rootBlocks.plist 删除
        NSString *documentPath = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) lastObject];
        NSString *filePath = [documentPath stringByAppendingPathComponent:@"rootBlocks.plist"];
        NSMutableDictionary *readDic = [NSMutableDictionary dictionaryWithContentsOfFile:filePath];
        
        
        NSMutableArray *array = [NSMutableArray arrayWithArray:[readDic objectForKey:@"blocksData"]];
        int count = 0;
        for (int i = 0; i < [array count]; i++) {
            if ([[array[i] objectForKey:@"pk"] isEqualToString:[self.array[button.tag] objectForKey:@"pk"]]) {
                count = i;
            }
        }
        [array removeObjectAtIndex:count];
        [readDic setObject:array forKey:@"blocksData"];
        BOOL result = [readDic writeToFile:filePath atomically:YES];
        
        if (result) {
            NSLog(@"删除rootBlocks成功");
        } else {
            NSLog(@"删除rootBlocks失败");
        }
    }
}

- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
 #pragma mark - Navigation
 
 // In a storyboard-based application, you will often want to do a little preparation before navigation
 - (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender
 {
 // Get the new view controller using [segue destinationViewController].
 // Pass the selected object to the new view controller.
 }
 */

@end
